package controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.UserBean;

import java.sql.*;
import model.UserDAO;

/**
 * Servlet implementation class SignupServlet
 */
@WebServlet("/SignupServlet")
public class SignupServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SignupServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try
		{	    

		     UserBean user = new UserBean();
		     user.setEmail(request.getParameter("email"));
		     user.setPassword(request.getParameter("password"));
		     user.setName(request.getParameter("name") + " " + request.getParameter("surname"));
		     boolean genderbool;
		     String gender = request.getParameter("gender");
		     if (gender.equals("TRUE"))
		    	 genderbool = true;
		     else
		    	 genderbool = false;
		     user.setGenderMale(genderbool);
		     String birthdate = request.getParameter("year") + "-" + request.getParameter("month") + "-" + request.getParameter("day");
		     user.setBirthDate(Date.valueOf(birthdate));
		     user.setCity(request.getParameter("city"));
		     user.setRegion(request.getParameter("region"));
		     user.setCountry(request.getParameter("country"));
		     
		     System.out.println(user.getName());

		     user = UserDAO.signup(user);
			   		    
		     if (user.isValid())
		     {	        
		          HttpSession session = request.getSession(true);
		    	  session.setAttribute("failedLogin", false);
		          session.setAttribute("currentSessionUser",user); 
		          response.sendRedirect("LoginServlet?un=" + user.getEmail() + "&pw=" + user.getPassword()); //logged-in page      		
		     }
			        
		     else {
		    	  HttpSession session = request.getSession(true);
		    	  session.setAttribute("failedLogin", true);
		          response.sendRedirect("login.jsp"); //loopback to login page to display error message
		     }
		} 
				
				
		catch (Throwable theException) 	    
		{
		     System.out.println(theException); 
		}	}

}
